﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Truextend.Common.Data;
using Truextend.CoffeShop.Model;
using Truextend.CoffeShop.Bussiness.Interfaces;

namespace Truextend.CoffeShop.Bussiness
{
    public class DetailManager : Repository<Detail> , IDetailManager
    {
        IProductManager productManager = null;

        public DetailManager(IUnitOfWork unitOfWork , IProductManager productManager) : base(unitOfWork) {
            this.productManager = productManager;
        }

        public void AddDetailForProductID(Detail detail , int productId)
        {
            Product product = productManager.GetProductById(productId);

            detail.ProductReference.EntityKey = product.EntityKey;

            this.Add(detail);
        }

        public Detail GetLastDetail()
        {
            var context = (CoffeShopEntities)Context;

            var info = from p in context.Detail orderby p.DetailId descending select p;
            
            return info.First();
        }

        public IList<Detail> GetAllDetailsOfAnOrder(int orderId)
        {
            var context = (CoffeShopEntities)Context;
            var info = from p in context.Detail.Include("Product") where p.Order.OrderId == orderId select p;

            return info.ToList();
        }        

        public Detail GetDetailById(int detailId)
        {
            var context = (CoffeShopEntities)Context;
            var info = from p in context.Detail where p.DetailId == detailId select p;

            return info.First();
        }


        public void DeleteDetail(int detailId)
        {
            var context = (CoffeShopEntities)Context;

            var detail = (from p in context.Detail where p.DetailId == detailId select p).First();

            try {

                IList<Consumption> listConsumptions = (from p in context.Consumption where p.Detail.DetailId == detailId select p).ToList();

                foreach(var consumption in listConsumptions){
                    context.DeleteObject(consumption);
                }

            }catch(Exception){}                                   

            context.DeleteObject(detail);

            this.Save();

        }
    }
}
